import Taro from "@tarojs/taro"
import { login } from '@/api/user'
import { useDispatch } from './useStore'

export const checkSession = ()=>{
   return new Promise( async (resolve,reject)=>{
       await Taro.checkSession({
           success: function () {
               resolve(true)
           },
           fail: function () {
               reject(false)
           }
       })
   })
}

export const wechatLogin = async ()=>{
    return new Promise(async (resolve,reject)=>{
        let check = false;//await checkSession()
        if (!check){
            await Taro.getUserProfile({
                desc: '用于获取头像、昵称等基本信息.',
                success: async (ret) => {
                    //cloudID,encryptedData,iv,rawData,signature,userInfo
                    // const cloudID = ret.cloudID
                    // const signature = ret.signature
                    const iv = encodeURIComponent(ret.iv)
                    const encryptedData = encodeURIComponent(ret.encryptedData)
                    const userInfo = ret.userInfo
                    await Taro.login({
                        success: async (res) => {
                            const result = await login({code:res.code,iv,encryptedData,userInfo})
                            await useDispatch('setUserInfo', result)
                            resolve(result)
                        },
                        fail:(err)=>{
                            reject(err)
                        }
                    })
                },
                fail:(err)=>{
                    reject(err)
                }
            })
        }else{
            console.log("测试结果")
            resolve(true);
        }
    })
}
